package com.bvcode.ncopter.comms;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

public class WifiModule extends ICommunicationModule {
	
	//-----------------------------------------------------------------
	private Socket sock = null;
	private OutputStream out;
	private InputStream in;
	
	String ip;
	int port;

    public String getDeviceAddressString(){ 
		return ip + ":" + port;
    }
	
    public void serviceHandleStatusRequest(Message msg) {
		try {
			
			int state;
			if( !isConnected() ){
				state = MSG_NOT_CONNECTED_TO_DEVICE;
			}else {
				state = MSG_CONNECTED_TO_DEVICE;
			}
			msg.replyTo.send( Message.obtain(null, MSG_GET_STATE, state, 0 ) );
			
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	
	public int clientHandleState(Messenger mService, Message msg, Activity parent) {
		switch( msg.arg1 ){
			case MSG_NOT_CONNECTED_TO_DEVICE: // Enabled but not connected
				return NOT_CONNECTED;
				
			case MSG_CONNECTED_TO_DEVICE: // Connected
				return CONNECTED;
			
		}
		return 0;
	}	
	
	public Message handleOnActivityResult(Activity parent, int requestCode, int resultCode, Intent data){
		return null;
	}
	
	public void connect(String address) throws IOException {
		String[] spl = address.split(":");
		assert(spl.length == 2);
		ip = spl[0];
		port = Integer.parseInt(spl[1]);
		
		sock = new Socket(ip, port);
		in = sock.getInputStream();
		out = sock.getOutputStream();
	}

	public boolean isConnected(){
    	return sock != null && sock.isConnected();
    }

	public void disconnect() throws IOException {
		sock.close();
	}
	
	public int write(byte[] b) throws IOException{
		out.write(b);
		return b.length; // assume that all data was written.
	}

	public void setSocketNull() {
		sock = null;
		out = null;
		in = null;
	}


	@Override
	public int readByte(byte[] b, int offset, int length) throws IOException {
		// Overflow protection. If we reach 1000 bytes, something is wrong.
		if ( offset + in.available() >= b.length )
			offset = 0;
		
		offset += in.read(b, offset, length);

		return offset;
	}

	@Override
	public boolean available() throws IOException {
		return (in != null && in.available() > 0);
	}
}
